package com.dys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dys.entity.LoginUser;
import com.dys.entity.SysUser;
import com.dys.mapper.MenuMapper;
import com.dys.mapper.RoleMapper;
import com.dys.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @Author: 疾风
 * @ClassName: UserDetailsServiceImpl
 * @Description: 根据用户名查询用户信息
 * @CreateDate: 2024/12/13
 * @Version: v1.0.0
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName, username);
        SysUser user = userMapper.selectOne(wrapper);
        // 查不到用户信息直接抛出异常
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户名or密码错误!!!");
        }
        // TODO:查询用户权限信息，添加到LoginUser中,权限暂时先写死,封装到List集合中
        // List<String> list = new ArrayList<>(List.of("test"));
        List<String> list = menuMapper.selectPermsByUserId(user.getUserId());
        // TODO: 查询当前用户拥有的角色信息,添加到LoginUser中
        List<String> roles = roleMapper.selectRolesByUserId(user.getUserId());
        // 方法的返回值是 UserDetails接口类型,需要返回自定义的实现类
        return new LoginUser(user, list,roles);
    }
}
